package com.lixin.demo.service.impl;

import com.lixin.demo.entity.Order;
import com.lixin.demo.mapper.OrderMapper;
import com.lixin.demo.service.AccountService;
import com.lixin.demo.service.OrderService;
import com.lixin.demo.service.ProductService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductService productService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    @GlobalTransactional
    public int createOrder(
            Long accountId, // 购买账号id
            Long productId, // 购买商品id
            int num // 购买数量
    ) {

        // 减商品库存
        int reduceStockResult = productService.reduceStock(productId, num);

        // 账号扣款
        int reduceBalanceResult = accountService.reduceBalance(accountId, productService.getTotalPrice(productId, num));

        // 创建订单
        Order order = new Order();
        order.setSerial(UUID.randomUUID().toString());
        order.setAccountId(accountId);
        order.setProductId(productId);
        int createOrderResult = orderMapper.createOrder(order);

        int age = 5 / 0;

        return createOrderResult;
    }

}
